package ren.yugong.fileutil;

import java.io.*;

public class TxtTemplateSplitReadStream<T> implements TxtReadStream<T> {

    private TxtTemplateModel<T> templateModel;
    private BufferedReader reader;

    protected TxtTemplateSplitReadStream(TxtTemplateModel<T> templateModel) {
        this.templateModel = templateModel;
    }

    @Override
    public void open(File file) {
        String charset = templateModel.getCharset();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public T read() {
        T t = null;
        try {
            String line = reader.readLine();
            t = TxtLineObject.object(line, templateModel.getTxtTemplateCls());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    @Override
    public void close() {
        try {
            if (null != reader) reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
